<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProductById } from '@/services/product'
import { useCartStore } from '@/stores/cart'

const route = useRoute()
const router = useRouter()
const product = ref(null)
const loading = ref(false)
const cart = useCartStore()
const addToCartLoading = ref(false)
// 记录当前页面的商品ID
const currentProductId = ref(null)
// 只显示当前商品的购物车信息
const currentProductCartItems = computed(() => {
  if (!currentProductId.value) return []
  // 查找与当前商品ID匹配的购物车项
  return cart.items.filter(item => 
    item.skuId === currentProductId.value || 
    item.id === currentProductId.value || 
    item.productId === currentProductId.value
  )
})

async function loadProduct(id) {
  if (!id) return
  loading.value = true
  try {
    const res = await getProductById(id)
    // 处理不同格式的响应数据
    if (res?.code === 200) {
      product.value = res.data
    } else if (res && typeof res === 'object' && !res.code) {
      // 直接使用返回的对象作为商品数据
      product.value = res
    } else {
      product.value = null
    }
  } catch (error) {
    console.error('加载商品详情失败:', error)
    product.value = null
  } finally {
    loading.value = false
  }
}

async function handleAddToCart() {
  if (!product.value) return
  
  // 获取当前商品ID
  const productId = product.value.id || product.value.skuId || product.value.productId
  
  // 检查购物车中是否已存在该商品
  const isProductInCart = cart.items.some(item => 
    item.skuId === productId || 
    item.id === productId || 
    item.productId === productId
  )
  
  // 如果商品已在购物车中，显示确认对话框
  if (isProductInCart) {
    const userConfirmed = confirm('您已购买过此商品，请确认是否再次购买')
    // 如果用户取消，直接返回
    if (!userConfirmed) {
      return
    }
  }
  
  addToCartLoading.value = true
  try {
    const payload = {
      productId: productId,
      buyQuantity: 1
    }
    
    const res = await cart.addItemApi(payload)
    
    if (res?.code === 200) {
      // 保存当前商品ID，只显示该商品的购物车信息
      currentProductId.value = payload.productId
      // 显示成功提示
      alert('已成功加入购物车！')
      
      // 滚动到购物车区域
      const cartElement = document.getElementById('cart-section')
      if (cartElement) {
        cartElement.scrollIntoView({ behavior: 'smooth' })
      }
    } else {
      alert('加入购物车失败，请重试')
    }
  } catch (error) {
    // 处理常见错误类型
    if (error.code === 'ECONNREFUSED') {
      alert('无法连接到服务器，请稍后再试')
    } else if (error.response && error.response.status === 403) {
      alert('权限不足，请先登录')
      // 重定向到登录页面
      router.push('/login')
    } else {
      alert('加入购物车失败，错误: ' + (error.message || '未知错误'))
    }
  } finally {
    addToCartLoading.value = false
  }
}

onMounted(async () => {
  await loadProduct(route.params.id)
  await cart.reload()
})

watch(() => route.params.id, async (id) => {
  // 切换商品时重置当前商品ID
  currentProductId.value = null
  await loadProduct(id)
  await cart.reload()
})
// 处理购物车商品数量变化
async function handleQuantityChange(item, change) {
  const newQuantity = Math.max(1, (item.qty || item.quantity || 1) + change)
  await handleQuantityUpdate(item, newQuantity)
}

// 处理输入框数量变化
async function handleQuantityInputChange(item, event) {
  let newQuantity = parseInt(event.target.value, 10)
  // 确保数量至少为1
  newQuantity = isNaN(newQuantity) ? 1 : Math.max(1, newQuantity)
  await handleQuantityUpdate(item, newQuantity)
}

// 更新商品数量
async function handleQuantityUpdate(item, newQuantity) {
  try {
    const payload = {
      cartId: item.id || item.skuId || item.productId, // 确保传递cartId
      buyQuantity: newQuantity
    }
    
    console.log('更新商品数量请求参数:', payload)
    const startTime = Date.now()
    const res = await cart.updateQtyApi(payload)
    const endTime = Date.now()
    
    console.log('更新商品数量请求耗时:', endTime - startTime, 'ms')
    console.log('更新商品数量响应结果:', res)
    
    // 检查响应状态
    if (res?.code === 200) {
      // 更新成功后重新加载购物车数据，确保UI显示最新数量
      await cart.reload()
      console.log('更新商品数量成功，当前数量:', newQuantity)
    } else {
      console.log('更新数量失败，后端返回非200状态码:', res?.code)
      alert('更新数量失败，请重试')
    }
  } catch (error) {
    console.error('更新商品数量失败:', error)
    // 处理常见错误类型
    if (error.code === 'ECONNREFUSED') {
      alert('无法连接到服务器，请稍后再试')
    } else if (error.response && error.response.status === 403) {
      console.error('403错误详情:', error.response.headers, error.response.data)
      alert('权限不足，请先登录')
      router.push('/login')
    } else {
      alert('更新数量失败，错误: ' + (error.message || '未知错误'))
    }
  }
}

// 删除购物车商品
async function handleRemoveItem(itemId) {
  if (confirm('确定要从购物车中删除该商品吗？')) {
    try {
      const res = await cart.removeItemsApi([itemId])
      
      if (res?.code !== 200) {
        alert('删除失败，请重试')
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      alert('删除失败，请重试')
    }
  }
}

// 去结算
function handleCheckout() {
  router.push('/checkout')
}


</script>

<template>
  <div class="container product">
    <div class="gallery">
      <img v-if="product?.productImage || product?.image" :src="product?.productImage || product?.image" :alt="product?.productName || product?.name || product?.title || '商品图片'" />
    </div>
    <div class="info">
      <h1>{{ product?.productName || product?.name || product?.title || '未命名商品' }}</h1>
      <div class="price" v-if="product && (product.price !== undefined || product.unitPrice !== undefined)">
        ￥{{ Number(product?.price || product?.unitPrice).toFixed(2) }}
      </div>
      <div class="stock" v-if="product && (product.stock !== undefined)">库存：{{ product?.stock }}</div>
      <div class="description" v-if="product?.brief || product?.description || product?.desc">
        {{ product?.brief || product?.description || product?.desc }}
      </div>
      <div class="actions">
        <button 
          class="btn btn-ghost" 
          :disabled="!product || addToCartLoading"
          @click="handleAddToCart"
        >
          {{ addToCartLoading ? '加入中...' : '加入购物车' }}
        </button>
        <button class="btn btn-primary" :disabled="!product">立即购买</button>
      </div>
      <div v-if="loading" class="muted">加载中...</div>
      <div v-else-if="!product" class="muted">商品信息加载失败，请稍后再试</div>
    </div>
  </div>
  
  <!-- 购物车区域 - 只显示当前商品的购物车信息 -->
  <div id="cart-section" class="container cart-section">
    <div class="cart-header">
      <h2>购物车</h2>
      <div class="cart-summary">
        <span>共 {{ currentProductCartItems.length && currentProductCartItems[0] ? (currentProductCartItems[0].qty || currentProductCartItems[0].quantity || 0) : 0 }} 件商品</span>
        <span class="total-price">合计：￥{{ currentProductCartItems.length && currentProductCartItems[0] && currentProductCartItems[0].price !== undefined ? Number((currentProductCartItems[0].qty || currentProductCartItems[0].quantity || 0) * currentProductCartItems[0].price).toFixed(2) : '0.00' }}</span>
      </div>
    </div>
    
    <div class="cart-content">
      <table v-if="currentProductCartItems.length > 0">
        <thead>
          <tr>
            <th>商品</th>
            <th>单价</th>
            <th>数量</th>
            <th>小计</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in currentProductCartItems" :key="item.skuId || item.id">
            <td class="product-info">
              <img v-if="item.image" :src="item.image" alt="{{ item.title }}" class="product-image" />
              <span>{{ item.title || item.name || '' }}</span>
            </td>
            <td v-if="item && item.price !== undefined">￥{{ Number(item.price).toFixed(2) }}</td>
            <td class="quantity-control">
              <button 
                class="btn quantity-btn" 
                @click="handleQuantityChange(item, -1)"
                :disabled="item && (item.qty || item.quantity || 1) <= 1"
              >
                -
              </button>
              <input 
                type="number" 
                :value="item.qty || item.quantity || 1" 
                min="1" 
                class="quantity-input"
                @change="handleQuantityInputChange(item, $event)"
              />
              <button 
                class="btn quantity-btn" 
                @click="handleQuantityChange(item, 1)"
              >
                +
              </button>
            </td>
            <td v-if="item && item.price !== undefined">￥{{ Number((item.qty || item.quantity || 1) * item.price).toFixed(2) }}</td>
            <td>
              <button 
                class="btn btn-danger"
                @click="handleRemoveItem(item.skuId || item.id)"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-else-if="currentProductId && currentProductId.value" class="empty-cart">
        该商品尚未添加到购物车，点击"加入购物车"按钮添加
      </div>
      
      <div v-else class="empty-cart">
        选择商品后可以查看其购物车信息
      </div>
    </div>
    
    <div class="cart-footer" v-if="currentProductCartItems.length > 0">
      <button class="btn btn-primary checkout-btn" @click="handleCheckout">去结算</button>
    </div>
  </div>
</template>

<style scoped>
.product { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 40px; }
.gallery { height: 420px; background: #fff; border: 1px solid var(--border); border-radius: var(--radius); }
.price { color: var(--primary); font-size: 20px; font-weight: 700; margin: 8px 0; }
.actions { display: flex; gap: 12px; margin-top: 12px; }
button { padding: 10px 16px; }

/* 购物车样式 */
.cart-section {
  margin-top: 40px;
  padding: 20px;
  background: #fff;
  border: 1px solid var(--border);
  border-radius: var(--radius);
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border);
}

.cart-header h2 {
  margin: 0;
  font-size: 20px;
}

.cart-summary {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-price {
  color: var(--primary);
  font-size: 18px;
  font-weight: 700;
}

.cart-content table {
  width: 100%;
  border-collapse: collapse;
}

.cart-content th,
.cart-content td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid var(--border);
}

.cart-content th {
  background-color: #f9f9f9;
  font-weight: 700;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border: 1px solid var(--border);
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--border);
  background: #fff;
  cursor: pointer;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-input {
  width: 60px;
  height: 28px;
  text-align: center;
  border: 1px solid var(--border);
  border-radius: 4px;
}

.btn-danger {
  background-color: #ff4d4f;
  color: white;
  border: none;
}

.btn-danger:hover {
  background-color: #ff7875;
}

.empty-cart {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 16px;
}

.cart-footer {
  margin-top: 20px;
  text-align: right;
}

.checkout-btn {
  background-color: var(--primary);
  color: white;
  border: none;
  padding: 12px 24px;
  font-size: 16px;
}

.checkout-btn:hover {
  opacity: 0.9;
}
</style>


